package com.kaifamiao.sync;

public class WithdrawTask implements Runnable {

    private Account account;
    private long amount;

    private WithdrawTask(Account account, long amount) {
        this.account = account;
        this.amount = amount;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for ( int i = 0; i < 3; i++ ) {
            // 被 synchronized 修饰的代码块被称作 同步代码块
            synchronized ( account ) { // enter monitor
                if (account.enough) {
                    System.out.printf("%s开始取钱，当前余额为: %d\n", name, account.balance);
                    Thread.yield();
                    account.balance -= amount; // 取款
                    account.enough = false; // 钱不够了
                    Thread.yield();
                    System.out.printf("%s取钱结束，当前余额为: %d\n", name, account.balance);
                    continue;
                }
                System.out.printf("余额不足，%s取钱失败\n", name);
            } // exit monitor
        }
    }

    public static void launch(String name, Account account, long amount) {
        Runnable runnable = new WithdrawTask( account, amount);
        Thread t = new Thread(runnable, name);
        t.start();
    }
}
